package org.example.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@PropertySource(value = "classpath:dynamic-datasource.properties", encoding = "utf-8")
public class PropertyConfiger {

    @Bean("primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean("secondDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondDataSource(){
        return DataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DataSource dynamicDataSource(){
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceMap.put("d1",primaryDataSource());
        dataSourceMap.put("d2",secondDataSource());

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        // 需要设置的多数据源
        dynamicDataSource.setTargetDataSources(dataSourceMap);

        // 主数据源/默认数据源
        dynamicDataSource.setDefaultTargetDataSource(primaryDataSource());
        return dynamicDataSource;
    }

}
